import cv2
import os
from tqdm import tqdm


def Video2Pic(videoPath, videoName, imgPath, frame_count, interval):
    print("\nStar to convert [%s] ...." % videoName)
    print("Start name = ", frame_count + 1)
    cap = cv2.VideoCapture(videoPath + '\\' + videoName)
    if cap.isOpened() is False:
        print("[%s] can't open!" % videoName)
        return frame_count
    FpsCount = -1
    FrameTotal = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    for i in tqdm(range(FrameTotal)):
        suc, frame = cap.read()
        if suc is False:
            break
        FpsCount += 1
        if (FpsCount % interval) != 0:
            continue
        frame_count += 1
        # cv2.imwrite(imgPath + "/%08d.jpg" % frame_count, frame)
        cv2.imencode('.jpg', frame)[1].tofile(imgPath + "/%08d.jpg" % frame_count)
        # cv2.imencode('.bmp', frame)[1].tofile(imgPath + "/%08d.bmp" % frame_count)

    cap.release()
    return frame_count


frame_count = 0  # 命名起始值
interval = 8  # 每interval帧把1帧输出成图片
file_dir = r'G:\Temp\新建文件夹\video_RemoveLimit'
ImgPath = r"G:\Temp\Temp10"
FileType = ['MP4', 'mp4', 'm4v', 'TS']
# EndWith = 'A'

UnknowFileType = []

for root, dirs, files in os.walk(file_dir):
    print("Deal [%s] ..." % root)
    OutPutPath = root.replace(file_dir, ImgPath)
    if os.path.exists(OutPutPath) is False:
        os.makedirs(OutPutPath)
    for file in files:
        if file.split(".")[-1] in FileType:
            # if file.split(".")[0][-1] in EndWith:
            frame_count = Video2Pic(root, file, OutPutPath, frame_count, interval)
        elif file.split(".")[-1] not in UnknowFileType:
            UnknowFileType.append(file.split(".")[-1])

print("-----------------------共%d张图片----------------------------" % frame_count)
print("Unknow files type：", UnknowFileType)
